package com.example.core.document;

import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;

import java.util.List;
import java.util.Optional;

public class HtmlElement {
    private final Element element;

    private HtmlElement(Element element) {
        this.element = element;
    }

    public static HtmlElement of(Element element) {
        return new HtmlElement(element);
    }

    public Element origin() {
        return element;
    }

    public List<HtmlElement> xpath(String exp) {
        return element.selectXpath(exp).stream().map(HtmlElement::of).toList();
    }

    public Optional<HtmlElement> xpath(String exp, int index) {
        return getOne(xpath(exp), index);
    }

    private Optional<HtmlElement> getOne(List<HtmlElement> elements, int index) {
        return elements.isEmpty() ? Optional.empty() : Optional.of(elements.get(index));
    }

    public List<HtmlElement> getElementsByClass(String className) {
        return element.getElementsByClass(className).stream().map(HtmlElement::of).toList();
    }

    public Optional<HtmlElement> getElementsByClass(String className, int index) {
        return getOne(getElementsByClass(className), index);
    }

    public List<HtmlElement> getElementsByTag(String tagName) {
        return element.getElementsByTag(tagName).stream().map(HtmlElement::of).toList();
    }

    public Optional<HtmlElement> getElementsByTag(String tagName, int index) {
        return getOne(getElementsByTag(tagName), index);
    }

    public Attribute attribute(String key) {
        return element.attribute(key);
    }

    public String text() {
        return element.text();
    }

    public HtmlElement child(int index) {
        return of(element.child(index));
    }
}
